package com.easylinkin.linkappapi.penetsecuremanage.controller;

import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.penetsecuremanage.dto.RailLinkappOrgInfoDTO;
import com.easylinkin.linkappapi.penetsecuremanage.dto.RailLinkappOrgResponsibilityDTO;
import com.easylinkin.linkappapi.penetsecuremanage.entity.RailLinkappOrgInfo;
import com.easylinkin.linkappapi.penetsecuremanage.service.IRailLinkappOrgInfoService;
import com.easylinkin.linkappapi.penetsecuremanage.service.IRailLinkappOrgResponsibilityService;
import com.easylinkin.linkappapi.penetsecuremanage.vo.RailLinkappOrgInfoVO;
import com.easylinkin.linkappapi.penetsecuremanage.vo.RailLinkappOrgResponsibilityVO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Objects;

/**后台穿透式安全管理/部门信息接口类
 * @author lyk
 * @date 2025/6/18 下午 5:10
 */
@RestController
@RequestMapping("/orgInfo")
public class RailLinkappOrgInfoController {

    @Autowired
    private  IRailLinkappOrgInfoService railLinkappOrgInfoService;
    @Autowired
    private IRailLinkappOrgResponsibilityService railLinkappOrgResponsibilityService;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;
    /**部门信息列表查询接口
     * @param dto
     * @return
     */
    @PostMapping(value = "/list")
    public RestMessage list(@RequestBody RailLinkappOrgInfoDTO dto){
        List<RailLinkappOrgInfoVO> result = railLinkappOrgInfoService.getList(dto);
        /**
         * 如果没有部门信息,进行责进行初始化
         */
        if(result.size() == 0){
            railLinkappOrgResponsibilityService.initTemplate();
            result = railLinkappOrgInfoService.getList(dto);
        }
        return RestBuilders.successBuilder(result).build();
    }

    /**
     * 部门名称编辑接口
     * @param dto
     * @return
     */
    @PostMapping(value = "/edit")
    public RestMessage edit(@RequestBody RailLinkappOrgInfoDTO dto){
        if (StringUtils.isEmpty(dto.getId())){
            return RestBuilders.failureMessage("记录id不能为空");
        }
        String orgName = dto.getName();
        if (dto.getName().length()>10){
            return RestBuilders.failureMessage("部门名称不能超过10个字符");
        }
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        Integer number = railLinkappOrgInfoService.countByOrgName(tenantId,orgName);
        if (number>0){
            return RestBuilders.failureMessage("部门名称重复");
        }
        RailLinkappOrgInfo byId = railLinkappOrgInfoService.getById(dto.getId());
        if (Objects.isNull(byId)){
            return RestBuilders.failureMessage("编辑的记录不存在");
        }
        railLinkappOrgInfoService.edit(dto);
        return RestBuilders.successBuilder("操作成功").build();
    }

    /**
     *  部门排序设置接口
     * @param id 记录id
     * @param sortType 排序类型 0:上移动 1:下移动
     * @return
     */
   @GetMapping(value = "/sortIndex.edit")
   public RestMessage sortIndexEdit(String id,Integer sortType){
        if (StringUtils.isEmpty(id)){
            return RestBuilders.failureMessage("记录id不能为空");
        }
        if (Objects.isNull(sortType)){
            return RestBuilders.failureMessage("排序操作类型不能为空");
        }
        railLinkappOrgInfoService.sortIndexEdit(id,sortType);
        return RestBuilders.successBuilder("操作成功").build();
   }

    /**
     * 部门删除接口
     * @param id 记录id
     * @return
     */
   @GetMapping(value = "/del")
   public RestMessage del(String id){
       if (StringUtils.isEmpty(id)){
           return RestBuilders.failureMessage("记录id不能为空");
       }
       railLinkappOrgInfoService.del(id);
       return RestBuilders.successBuilder("操作成功").build();
   }

    /**
     *  组织穿透部门新增加导入职责接口
     * @param orgName 部门名称
     * @param file    模板，需要导入的内容（可选）
     * @return
     */
   @PostMapping(value = "/add")
   public RestMessage add(@RequestPart("orgName")String orgName,@RequestPart(value = "file", required = false) MultipartFile file){
       if (StringUtils.isEmpty(orgName)){
           return RestBuilders.failureMessage("部门名称不能为空不能为空");
       }
       if (orgName.length()>10){
           return RestBuilders.failureMessage("部门名称不能超过10个字符");
       }
       String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
       Integer number = railLinkappOrgInfoService.countByOrgName(tenantId,orgName);
       if (number>0){
           return RestBuilders.failureMessage("部门名称重复");
       }
       railLinkappOrgInfoService.add(orgName,file);
       return RestBuilders.successBuilder("操作成功").build();
   }
    /**
     *  组织穿透部门导入职责模板下载接口
     * @param request
     * @param response
     */
    @GetMapping(value = "/orgInfoTemplate.down")
    public void rosterTemplateDown(HttpServletRequest request, HttpServletResponse response){
        String title = "部门职责信息";
        String fileName =  "orgInfoTemplate.xlsx";
        try {
            OutputStream outputStream = OutputStreamUtil.getOutputStream(request, response, fileName);
            String keyValue = "序号:number,职责内容:content";
            ExcelTools.exportExcel(outputStream, keyValue, RailLinkappOrgResponsibilityDTO.creatExcel(), ExcelConstant.XLSX,title);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException("excel导出失败！IOException异常");
        } catch (Exception e) {
            throw new RuntimeException("excel导出失败！");
        }
    }




}
